/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include <stdlib.h>
#include <string.h>

extern "C" void cfltcvt(double value, char *buffer, char fmt, int precision) {
	int decpt, sign, exp, pos;
	const char *digits = NULL;
	char cvtbuf[80];
	int capexp = 0;
	int magnitude;
	if (fmt == 'G' || fmt == 'E') {
		capexp = 1;
		fmt += 'a' - 'A';
	}
	if (fmt == 'g') {
		digits = ecvtbuf(value, precision, &decpt, &sign, cvtbuf);
		magnitude = decpt - 1;
		if (magnitude < -4  ||  magnitude > precision - 1) {
			fmt = 'e';
			precision -= 1;
		} else {
			fmt = 'f';
			precision -= decpt;
		}
	}
	if (fmt == 'e') {
		digits = ecvtbuf(value, precision + 1, &decpt, &sign, cvtbuf);
		if (sign) {
			*buffer++ = '-';
		}
		*buffer++ = *digits;
		if (precision > 0) {
			*buffer++ = '.';
		}
		memcpy(buffer, digits + 1, precision);
		buffer += precision;
		*buffer++ = capexp ? 'E' : 'e';
		if (decpt == 0) {
			if (value == 0.0) {
				exp = 0;
			} else {
				exp = -1;
			}
		} else {
			exp = decpt - 1;
		}
		if (exp < 0) {
			*buffer++ = '-';
			exp = -exp;
		} else {
			*buffer++ = '+';
		}
		buffer[2] = (exp % 10) + '0';
		exp = exp / 10;
		buffer[1] = (exp % 10) + '0';
		exp = exp / 10;
		buffer[0] = (exp % 10) + '0';
		buffer += 3;
	} else if (fmt == 'f') {
		digits = fcvtbuf(value, precision, &decpt, &sign, cvtbuf);
		if (sign) {
			*buffer++ = '-';
		}
		if (*digits) {
			if (decpt <= 0) {
				*buffer++ = '0';
				*buffer++ = '.';
				for (pos = 0; pos < -decpt; pos++) {
					*buffer++ = '0';
				}
				while (*digits) {
					*buffer++ = *digits++;
				}
			} else {
				pos = 0;
				while (*digits) {
					if (pos++ == decpt) {
						*buffer++ = '.';
					}
					*buffer++ = *digits++;
				}
			}
		} else {
			*buffer++ = '0';
			if (precision > 0) {
				*buffer++ = '.';
				for (pos = 0; pos < precision; pos++) {
					*buffer++ = '0';
				}
			}
		}
	}
	*buffer = '\0';
}
